# !/usr/bin/env python
# -*- coding: utf-8 -*-

import multiprocessing
import time
import urllib.request


def download_file(url, filename):
    urllib.request.urlretrieve(url, filename)
    print(f"Downloaded {filename} from {url}")


def worker(name):
    print(f"Worker {name} is starting.")
    time.sleep(2)
    print(f"Worker {name} is exiting.")


def square_sum(numbers):
    return sum(x ** 2 for x in numbers)


def demo1():
    pool = multiprocessing.Pool(processes=2)
    pool.map(worker, ["A", "B"])
    pool.close()
    pool.join()


# 并行计算， 大规模数据处理或计算密集型任务时，使用多进程可以显著提高程序的运行速度
def demo2():
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    num_processes = 4
    pool = multiprocessing.Pool(processes=num_processes)
    chunk_size = len(numbers) // num_processes
    chunks = [numbers[i:i + chunk_size] for i in range(0, len(numbers), chunk_size)]
    results = pool.map(square_sum, chunks)
    total_sum = sum(results)
    print("Total square sum:", total_sum)
    pool.close()
    pool.join()


#  IO密集型任务 大量IO操作的任务中，如文件读写、网络请求等，使用多进程可以避免IO阻塞，提高程序的响应速度
def demo3():
    urls = [
        ("https://example.com/file1.txt", "file1.txt"),
        ("https://example.com/file2.txt", "file2.txt"),
        ("https://example.com/file3.txt", "file3.txt")
    ]
    num_processes = len(urls)
    pool = multiprocessing.Pool(processes=num_processes)
    pool.starmap(download_file, urls)
    pool.close()
    pool.join()


if __name__ == "__main__":
    # demo1()
    # demo2()
    demo3()
